package list;

public class MyArrayList {

    //data 来保存所有元素
    public String[] data = null;
    //size 来标识实际存储元素的多少
    public int size = 0;

    public MyArrayList(){
        data = new String[10];
    }

    //capacity 来表示容量
    public MyArrayList(int capacity){
        if (capacity <= 10){
            capacity = 10;
            data = new String[capacity];
        }
        data = new String[capacity];
    }

    //扩容操作
    public void recapacity(){
        //1.先将容量扩大 1.5 倍
        String[] newData = new String[(int)(data.length * 1.5)];
        //2.复制到新的数组中
        for (int i = 0; i < data.length; i++){
            newData[i] = data[i];
        }
        //3.新数组代替旧数组
        data = newData;
    }

    //尾插
    public void add(String elem){
        //判断是否需要扩容
        if (size >= data.length){
            recapacity();
        }
        data[size] = elem;
        size++;
    }

    //指定位置插入插
    public void add(int index, String elem){
        //判断下标是否合法
        if (index < 0 || index > data.length){
            //抛出异常
            throw new IndexOutOfBoundsException("Index: " + index + ", size " + size);
        }
        //判断是否需要扩容
        if (size >= data.length){
            recapacity();
        }
        //将插入元素后面的元素进行移动
        for (int i = size - 1; i >= index; i--){
           data[i + 1] = data[i];
        }
        //最后插入元素
        data[index] = elem;
        size++;
    }
    public String toString(){
        //使用StringBuilder 类来拼接字符串
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("[");
        for (int i = 0; i < size ; i++){
            stringBuilder.append(data[i]);
            if (i < size - 1){
                stringBuilder.append(",");
            }
        }
        stringBuilder.append("]");
        return stringBuilder.toString();
    }


    public static void test1(){
        MyArrayList list = new MyArrayList();
        list.add("hello");
        list.add("world");
        list.add("world");
        list.add("world");
        list.add("world");
        list.add("world");
        list.add("world");
        list.add("world");
        list.add("world");
        list.add("world");
        list.add("world");
        list.add("world");
        System.out.println(list);
    }
    public static void test2(){
        MyArrayList list = new MyArrayList();
        list.add(0, "aaa");
        list.add(0, "bb");
        list.add(0, "c");
        list.add(0, "ddddd");
        list.add(2, "x");
        System.out.println(list);
    }
    public static void main(String[] args) {
        //test1();
        //test2();
    }
}
